package com.niit.drugsmanager.service.Impl;

import com.niit.drugsmanager.entity.User;
import com.niit.drugsmanager.repository.UserRepository;
import com.niit.drugsmanager.service.UserService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User createUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User getUser(String email, String password) {
        return userRepository.findUserByEmailAndPassword(email, password);
    }

    @Override
    public @Nullable User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public Page<User> findUsers(String search, Pageable pageable) {
        if(search == null || search.isEmpty()) {
            return userRepository.findAll(pageable);
        }
        return userRepository.findUserByUsernameContainingOrEmailContaining(search, search, pageable);
    }

    @Override
    public boolean removeUser(Long id) {
        Integer i = userRepository.removeUserById(id);
        return i != null;
    }

    @Override
    public User updatePermissionAndRole(Long uid, Integer permission, Integer role) {
        User user = userRepository.findById(uid).orElse(null);
        if(user != null) {
            user.setPermission(permission);
            user.setRole(role);
            return userRepository.save(user);
        }
        return null;
    }


}
